/*
 * 滚动有时间需要重写
*/
function lrScroll(options){
	var defaults = {
			obj:'',				    //滚动对象
			sNum:'',			    //滚动单位个数
            spacing:0,				//单位间距
			rowNum:1,				//一列上有几个
			auto:false,
			navNumShow:false,
            fullScreen:false,
            autoDelay:3000,
            anTime:400,
            autoHideNav:true,
            scrollType:"hor",
			navShow:function($scroll,stepNum,scrollNav){
				var tempNavArr = [];
				for(var num=0;num < stepNum;num++){
					if(opts.navNumShow){
						tempNavArr.push("<a title=''>"+(num+1)+"</a>");
					}else{
						tempNavArr.push("<a title=''></a>");
					}
				}
				scrollNav.html(tempNavArr.join(""));
			},
            callback:function($scroll,i){},
            nextCb: function(){}
		};
		
	var opts = $.extend(defaults, options),
        $scroll = $(opts.obj),
        Animate = {},
        mouseMoveTemp = 0;
	if(!$scroll.length){return }	//节点不存在返回
    (opts.scrollType == "ver") ? $scroll.addClass("lrscroll-ver") : $scroll.addClass("lrscroll-hor");
	
	var $scrollcon = $(".scrollcon",$scroll),
		$prev = $scroll.children(".prev"),
		$next = $scroll.children(".next"),
		$scrollNav = $(".scrollnav",$scroll),
		$scrollList = $(".scrolllist",$scroll),
		len = Math.ceil($scrollList.children("li").length/opts.rowNum),
		firstW = (opts.fullScreen) ? $(window).width() : $scrollList.find("li").eq(0).width(),
		firstH = $scrollList.find("li").eq(0).outerHeight();

	//设置宽度
    (opts.scrollType == "ver")? $scrollList.width($scrollcon.width()) : $scrollList.width( len*firstW+opts.spacing*len );

    //此功能有待后续完善
    if(opts.fullScreen){
        $scrollList.find("li").width($(window).width())
    }
	var	$scrollConSize = (opts.scrollType == "hor") ? $scrollcon.width() : $scrollcon.height(),		//滚动内容区域尺寸
		$scrollListSize = (opts.scrollType == "hor") ? $scrollList.width() : $scrollList.height(),	//滚动列表ul的尺寸
		$oneSize = (opts.scrollType == "hor") ? firstW : firstH,	//单位节点尺寸
		anSize = $oneSize*opts.sNum+(opts.sNum-1)*opts.spacing,		//单位节点尺寸*滚动单位个数+（滚动单位个数-1）*单位间距
		_anSize = anSize+opts.spacing,			//动画滚动距离
		page = 0;

	//i 得到可视尺寸内能显示几个尺寸单位
	var i = Math.ceil($scrollConSize/_anSize);

	//根据一个尺寸单位计算出可以产生几个几步数，减去可视尺寸内的尺寸单位 i 。
	var step = Math.ceil($scrollListSize/_anSize);
	var stepNum = step-i;

    opts.callback($scroll,i);     //回调

	var setInt;             //自动滚动定时器变量
    clearInterval(setInt);  //先清理一次

	//个数不够一屏幕返回
	if(len==1&&opts.autoHideNav){
		$scrollNav.hide();
		$prev.hide();
		$next.hide();
		return
	}
	
	if(len<=i){
		/*$scrollNav.hide();
		$prev.hide();
		$next.hide();*/
		return
	}
    //tools.log(opts.obj,step);
	//生成导航 插入数字
	opts.navShow($scroll,step,$scrollNav);
	
	var $scrollNavA = $scrollNav.children("a");
	addCur($scrollNavA.eq(0));
	
	//PREV
	$prev.click(function(){
		if(page==0){
            Animate.Animate("-="+_anSize*stepNum);
            page=stepNum;
            addCur($scrollNavA.eq(page));
        }else{
            Animate.Animate("+="+_anSize);
			page--;
			addCur($scrollNavA.eq(page));
		}
        return false
	});

	//NEXT
	$next.click(function(){
		if(page==stepNum){
			page = 0;
            Animate.Animate("0");
			addCur($scrollNavA.eq(page));
		}else{
            Animate.Animate("-="+_anSize);
			page++;
			addCur($scrollNavA.eq(page));
		}
        return false
	});

	//数字导航
	$scrollNav.on('click','a',function(){
		var thisIndex = $(this).index();
		page = thisIndex;
        Animate.Animate(-_anSize*thisIndex);
		addCur($(this));
        return false
	});

    //自动滚动
    $scroll.on({
            'mouseenter': function() {
                clearInterval(setInt);
            },
            'mouseleave':function(){
                clearInterval(setInt);
                if (opts.auto) {
                    setInt = setInterval(function () {
                        $next.trigger("click");
                    },opts.autoDelay);
                }
            },
            'mousemove':function(e){
                if(!mouseMoveTemp && $(e.target).closest(".lrscroll").length){
                    mouseMoveTemp = 1;
                    clearInterval(setInt);
                }
            }
    });
    if (opts.auto) {
        $scroll.trigger("mouseleave");
    }

    function addCur(obj){
        obj.addClass("cur").siblings("a").removeClass("cur");
    }

    Animate.Animate = function(anSize,i){
        if(opts.scrollType == "hor"){
            $scrollList.stop(true,true).animate({"left":anSize},opts.nextCb);
        }else if(opts.scrollType == "ver"){
            $scrollList.stop(true,true).animate({"top":anSize},opts.anTime);
        }
    };

}

/*
 * 参数说明：
 * scrollType取值为 fade   hor    ver 默认为fade
 */
function lrFocus(options){
    var opts = $.extend({
        obj:'div.focuscon',
        timeOut:'3000',
        scrollType:'fade',
        autoRun:true
    },options);

    $(opts.obj).each(function(){
        mainFun($(this))
    });
    function mainFun(obj){
        var i = 0;
        var delayTime;

        var $focus = obj,
            $focusUl    = $focus.children("div").children("ul"),
            $focusLi    = $focusUl.children("li"),
            $focusNum   = $focus.children(".focusnum"),
            $focusTit   = $focus.children(".focustit"),
            $focusPrev  = $focus.children(".prev"),
            $focusNext  = $focus.children(".next"),
            $focusUlH = $focusUl.height(),
            $focusLiW = $focusLi.width(),
            len = $focusLi.length;
        if(opts.scrollType == 'hor'){
            $focus.addClass("scrollHor")
        }else if(opts.scrollType == 'ver'){
            $focus.addClass("scrollVer")
        }
        //$focusLi.eq(0).css({"z-index":"10","display":"block"});//初始化
        $focusLi.eq(0).show();
        makeTit(0);

        //插入数字
        for(num=0;num<len;num++){
            $focusNum.append("<span></span>");
        }
        var focusNumSpan = $focusNum.children("span");
        focusNumSpan.eq(0).addClass("on");//初始化
        $focus.on('click','span',function(){
            var index = focusNumSpan.index($(this));
            Animate(index);
        });

        //各种事件
        $focusPrev.click(function(){
            if(i==0){i=len}
            Animate(i-1);
            i--;
        });
        $focusNext.click(function(){
            if(i==(len-1) ){i=-1}
            Animate(i+1);
            i++;
        });

        $focus.hover(function() {
            clearInterval(delayTime);
        },function() {
            clearInterval(delayTime);
            delayTime = setInterval(function(){
                Animate(i);
                i++;
                if(i == len ){i=0;}
            },opts.timeOut);
        });
        if(opts.autoRun){ $focus.trigger("mouseleave"); }

        //淡入淡出动画效果
        function Animate(i){
            if(opts.scrollType == 'fade'){
                //$focusLi.eq(i).css({"z-index":"10"}).fadeIn(400).siblings("li").css({"z-index":"1"}).fadeOut(400)
                $focusLi.eq(i).fadeIn(400).siblings("li").fadeOut(400);
            }else if(opts.scrollType == 'hor'){
                $focusUl.animate({"left":-($focusLiW*i)});
            }else{
                $focusUl.animate({"top":-($focusUlH*i)});
            }
            focusNumSpan.eq(i).addClass("on").siblings("span").removeClass("on");
            makeTit(i)
        }
        function makeTit(i){
            var titTxt = $focusLi.eq(i).children("a").attr("title");
            var titHref = $focusLi.eq(i).children("a").attr("href");
            $focusTit[0].innerHTML = '<a href='+titHref+'>'+titTxt+'</a>';
        }
    }
}


/*
 * 循环滚动
 */
(function($){
    //工具
    var tool = {
        log:function(log){
            return  window.console && console.log(log);
        }
    };
    //插件开始
    $.extend($.fn,{
        circularly:function(config){
            var opts = $.extend({
                getUrl:"",
                threshold:5,
                delayTime:2000,
                direction:"up",
                slipStop:true,
                spacing:0,
                sendParameters:function($scrollList,$li,page,len,i){
                    //($scrollList,$li,page,len,i) ->  $scrollList 滚动列表的jq对象,$li滚动列表的li的jq对象，更多返回值：滚动列表中li的个数：len,当前自增计数：i,当前页数：page
                    //return {postTime:$li.last().find(".fn-time").text().replace(/\s/g,"")}
                }
            },config);
            this.len = 0;
            this.each(function(index){
                var This = this, $this = $(this),
                    $scrollCon = $this.find(".scrollcon"),
                    $scrollList = $this.find(".scrolllist"),
                    $li = $scrollList.children("li"),
                    $temp = $this.find(".temp"),
                    oneSize = (opts.direction=="up") ? $li.eq(0).outerHeight()+opts.spacing : $li.eq(0).outerWidth()+opts.spacing;
                //tool.log($scrollList.height()-$scrollCon.height(),oneSize);
                if( $scrollList.height()-$scrollCon.height() >= 0 ){
                    scrollFn(This,$temp,$scrollList,oneSize);
                }
                return this;
            });
            function scrollFn(This,$temp,$scrollList,oneSize){
                var t= 0, t1= 0, i = 0,page = 1,recycle = [];
                var $li = $scrollList.children("li"),
                    anObj = (opts.direction=="up") ? {"top":-oneSize} : {"left":-oneSize};

                This.len = $li.length;

                function timeOutRun(){
                    //tool.log(opts.slipStop);
                    if(opts.slipStop){
                        clearTimeout(t);
                        clearTimeout(t1);
                    }
                    $scrollList.stop(true,true).animate(anObj,1000,function(){
                        i++;
                        //tool.log(This.len-i);
                        if( opts.getUrl && This.len>opts.threshold ){
                            if((This.len-i) == opts.threshold){
                                var postObj = $.extend(true,{page:page+1},opts.sendParameters($scrollList,$li,page,This.len,i));    //很难知道使用者到底需要哪些参数，开放出去可以自行定义
                                $.get(opts.getUrl,postObj,function(res){
                                    if(res.length>10){
                                        $scrollList.append(res);
                                        This.len = $scrollList.children("li").length;
                                        i = 0;
                                        page++
                                    }else{
                                        $scrollList.append($temp.html());
                                    }
                                });
                            }
                            $temp.append($scrollList.children("li").first());
                        }else{
                            $scrollList.append($scrollList.children("li").first());
                        }
                        $scrollList.css("top",0);
                    });
                    t = setTimeout(timeOutRun,opts.delayTime)
                }
                timeOutRun();
                $scrollList.on("mouseenter",function(){
                    //tool.log(opts.slipStop);
                    if(opts.slipStop){
                        clearTimeout(t);
                        clearTimeout(t1);
                    }
                }).on("mouseleave",function(){
                        if(opts.slipStop){
                            t1 = setTimeout(timeOutRun,600)
                        }
                    });
            }
        }
    });
})(jQuery);

